/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package form;

import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.CoordinateLayout;
import helper.ListRenderer;
import helper.MobileDownloader;
import helper.Util;
import java.io.IOException;

import midlet.MainMidlet;
import model.ItemMenu;
import model.ItemSms;

/**
 *
 * @author LegACy
 */
public class MainFormUi extends ParentForm implements ActionListener {

    //Members
    public String space = "       ";
    private List m_List;
    public ItemMenu item[];
    private Label leftBtn;
    private Label rightBtn;

    /**
     * Main form constructor
     * @param midlet    The midlet which runs the form
     * @param parent    The previous form
     * @param items     An Array of item information.
     */
    public MainFormUi(MainMidlet midlet, ParentForm parent, ItemMenu[] items, String prntMenu) {
        super(midlet, parent, null);

        Image bg = null;
        Image img = null;
        String URL = null;
        try {
//            img = Image.createImage("/res/image/parentLabel.png");
            URL = Util.getInstance().getBackgroung("menu");
            bg = Image.createImage(MobileDownloader.download(URL), 0, MobileDownloader.download(URL).length);
        } catch (Exception ex) {
            try {
                bg = Image.createImage(ParentForm.BG_IMAGE);
            } catch (IOException ex1) {
                ex1.printStackTrace();
            }
        }

        //Configure form
        //set baground
        this.getStyle().setBgImage(bg);
        this.setLayout(new CoordinateLayout(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayHeight()));
//        System.out.println(Display.getInstance().getDisplayWidth() + " " + Display.getInstance().getDisplayHeight());
        if (prntMenu != null) {
            Label parentMenu = new Label(space + prntMenu.trim() + space);
            parentMenu.setX(120);
            parentMenu.setY(50);
            parentMenu.getStyle().setMargin(Component.BOTTOM, 0);
            parentMenu.setAlignment(Label.CENTER);
            Font font = Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
            parentMenu.getStyle().setFont(font);
            parentMenu.getStyle().setBgImage(img);

            this.addComponent(parentMenu);
        }


        //Create list of item
        this.createItemList(items);

        //Add commandsContactsRenderer
        if (items[0].getType().equalsIgnoreCase("menu") && items[0].getParentId() == 0) {
            leftBtn = new Label("  open  ");
            leftBtn.setX(0);
            leftBtn.setY(Display.getInstance().getDisplayHeight() - 25);
            leftBtn.getStyle().setBgTransparency(0);
            this.addComponent(leftBtn);


            rightBtn = new Label("  exit  ");
            rightBtn.setX(Display.getInstance().getDisplayWidth() - 60);
            rightBtn.setY(Display.getInstance().getDisplayHeight() - 25);
            rightBtn.getStyle().setBgTransparency(0);
            this.addComponent(rightBtn);

        } else if (items[0].getType().equalsIgnoreCase("sms")) {
            leftBtn = new Label("   buy   ");
            leftBtn.setX(0);
            leftBtn.setY(Display.getInstance().getDisplayHeight() - 25);
            leftBtn.getStyle().setBgTransparency(0);

            this.addComponent(leftBtn);


            rightBtn = new Label("  back  ");
            rightBtn.setX(Display.getInstance().getDisplayWidth() - 60);
            rightBtn.setY(Display.getInstance().getDisplayHeight() - 25);
            rightBtn.getStyle().setBgTransparency(0);
            this.addComponent(rightBtn);

        } else {
            leftBtn = new Label("  open  ");
            leftBtn.setX(0);
            leftBtn.setY(Display.getInstance().getDisplayHeight() - 25);
//            leftBtn.getStyle().setBgImage(btn);
            leftBtn.getStyle().setBgTransparency(0);

            this.addComponent(leftBtn);


            rightBtn = new Label("  back  ");
            rightBtn.setX(Display.getInstance().getDisplayWidth() - 60);
            rightBtn.setY(Display.getInstance().getDisplayHeight() - 25);
            rightBtn.getStyle().setBgTransparency(0);
            this.addComponent(rightBtn);

        }
        this.addCommandListener(this);
    }

    /**
     * Create lists of items from item array
     * @param items The array containing items data.
     */
    private void createItemList(ItemMenu[] items) {
        //for
        String words = " ";
        for (int i = 0; i < Util.textLengh(items); i++) {
            words = words + " ";
        }

        items[0].setMenuName(items[0].getMenuName() + words);

        m_List = new List(items);
        m_List.setY(70);
        m_List.setListCellRenderer(new ListRenderer());
        m_List.setPreferredH(130);
        m_List.setPreferredW(300);
        this.addComponent(m_List);

    }

    /**
     * Key press listener.
     * @param keyCode The key code of the button being pressed.
     */
    public void keyPressed(int keyCode) {
        super.keyPressed(keyCode);

        //If action button is pressed, view item detail
        if (keyCode == -5) {
            ItemMenu menuSlc = (ItemMenu) m_List.getSelectedItem();
            if (menuSlc.getType().equalsIgnoreCase("menu")) {
                menuSelected(menuSlc.getId(), menuSlc.getMenuName());
            } else if (menuSlc.getType().equalsIgnoreCase("sms")) {
                smsSend(menuSlc);
            } else if (menuSlc.getType().equalsIgnoreCase("exit")) {
                this.midlet.notifyDestroyed();
            } else if (menuSlc.getType().equalsIgnoreCase("text")) {
                new SecondForm(this.midlet, this).show();
                this.disposeForm();
            }
        } else if (keyCode == -7) {
            System.out.println("pres -7 :" + rightBtn.getText().toString().trim());

            if (rightBtn.getText().toString().trim().equals("exit")) {
                this.midlet.notifyDestroyed();
            } else if (rightBtn.getText().toString().trim().equals("back")) {
                this.disposeForm();
            }


        } else if (keyCode == -6) {
            if (leftBtn.getText().toString().trim().equals("open")) {
                ItemMenu menuSlc = (ItemMenu) m_List.getSelectedItem();
                if (menuSlc.getType().equalsIgnoreCase("exit")) {
                    this.midlet.notifyDestroyed();
                } else if (menuSlc.getType().equalsIgnoreCase("text")) {
                    new SecondForm(this.midlet, this).show();
                } else {
                    menuSelected(menuSlc.getId(), menuSlc.getMenuName());
                }
            } else if (leftBtn.getText().toString().trim().equals("buy")) {
                ItemMenu menuSlc = (ItemMenu) m_List.getSelectedItem();
                System.out.println("id :" + menuSlc.getId() + " menu: " + menuSlc.getMenuName());
                smsSend(menuSlc);
            }
        }

    }

    private void smsSend(ItemMenu menuItem) {

        String[] array = null;
        try {
            array = Util.split(Util.getInstance().getSms(menuItem.getId()), "|");
            ItemSms sms = new ItemSms(array[0], array[1], array[2]);

            //call ConfirmForm
            new ConfirmForm(this.midlet, this, menuItem, sms).show();
        } catch (Exception ex) {
            Dialog.show("beavers admin", "Sorry, content is not available ! ", "OK", null);
        }


    }

    private void menuSelected(int parentId, String parenMenu) {

        String[] array = null;
        try {
            array = Util.split(Util.getInstance().getMenuByParentId(parentId), "####");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            ItemMenu[] ItemList = new ItemMenu[array.length - 1];
            for (int i = 0; i < array.length - 1; i++) {
                String[] data = Util.split(array[i], "|");
                Image icon = Image.createImage(MobileDownloader.download(data[3]), 0, MobileDownloader.download(data[3]).length);
                ItemList[i] = new ItemMenu(Integer.parseInt(data[0]), data[1], data[2], icon, Integer.parseInt(data[4]));
                //            System.out.println("item at[" + i + "]=" + ItemList[i].getMenuName());
            }

            //Create main form
            new MainFormUi(this.midlet, this, ItemList, parenMenu).show();

        } catch (IndexOutOfBoundsException ex) {
            Dialog.show("beavers admin", "Sorry, menu is not available ! ", "OK", null);
        }
    }
}
